/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.googlecode.mindlistening.util;

import com.googlecode.mindlistening.PropertiesStorage;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.SystemUtils;

/**
 *
 * @author ryan
 */
public class CouchLocator  {

    PropertiesStorage p_storage;



    public CouchLocator(PropertiesStorage p_storage) {
        this.p_storage = p_storage;
    }

    public String findCouchDB() {

        String previousExe = p_storage.loadProperty("couchdb");
        String embeddedCouchExe = locateEmbeddedCouchExe();

        String exeToUse = findBestExe(previousExe, embeddedCouchExe);
        if (exeToUse != null) {
            p_storage.storeProperty("couchdb", exeToUse);
        }
        return exeToUse;
    }

    protected String locateEmbeddedCouchExe() {
        // check the lib dir
        File lib = new File("lib");
        if (!lib.exists() || !lib.isDirectory()) return null;

        File[] dirs = lib.listFiles();
        File couchDBDir = findCouchDBDir(dirs);
        if (couchDBDir == null) return null;
        File couchdbBinDir = new File(couchDBDir, "bin");
        if (!couchdbBinDir.exists() || !couchdbBinDir.isDirectory()) return null;

        File couchDbBinFile = findCouchDbBinFile(couchdbBinDir);
        if (!couchDbBinFile.exists() || !couchDbBinFile.isFile()) return null;

        String fullExe = couchDbBinFile.getAbsolutePath();
        //p_storage.storeProperty("couchdb", fullExe);

        return fullExe;
    }

    private String findBestExe(String previousExe, String embeddedCouchExe) {
        if (previousExe == null && embeddedCouchExe == null) return null;
        if (embeddedCouchExe == null) return previousExe;
        return embeddedCouchExe;
    }

    public File findCouchDBDir(File[] dirs) {
        for (File file : dirs) {
            if (file.getName().startsWith("couchdb")) return file;
        }
        return null;
    }

    protected File findCouchDbBinFile(File couchdbBinDir) {
        File location = null;
        if (SystemUtils.IS_OS_WINDOWS) {
            location = new File(couchdbBinDir, "couchdb.bat");
        }
        else  {
            location  = new File(couchdbBinDir, "couchdb");

        }
        return location;
    }



}
